import type { FileProps } from "@/components/RefilePreview/types";
import { onUnmounted, ref } from "vue";
import axios from "axios";

export function useHooks(props: FileProps) {
  const excelOptions = {
    xls: props.fileType !== "xlsx", //预览xlsx文件设为false；预览xls文件设为true
    minColLength: 0, // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
    minRowLength: 0, // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
    widthOffset: 10, //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
    heightOffset: 10, //在默认渲染的列表高度上再加 Npx高
    beforeTransformData: workbookData => {
      return workbookData;
    }, //底层通过exceljs获取excel文件内容，通过该钩子函数，可以对获取的excel文件内容进行修改，比如某个单元格的数据显示不正确，可以在此自行修改每个单元格的value值。
    transformData: workbookData => {
      return workbookData;
    } //将获取到的excel数据进行处理之后且渲染到页面之前，可通过transformData对即将渲染的数据及样式进行修改，此时每个单元格的text值就是即将渲染到页面上的内容
  };
  const src = ref();
  const filePreviewRef = ref();
  /**
   * 渲染完成
   */
  const renderedHandler = () => {
    console.log("渲染完成");
  };
  /**
   * 渲染失败
   * @param e
   */
  const errorHandler = e => {
    console.log("渲染失败", e);
  };

  /**
   * 渲染文件
   */
  async function renderTheFile() {
    if (props.type === "local") {
      console.log("本地文件" + props.fileType);
      isImage(props.fileType) && localImagePreview(props.raw);
      isDoc(props.fileType) && localOfficePreview(props.raw);
      isText(props.fileType) && localTextPreview(props.raw);
      isVideo(props.fileType) && localVideoPreview(props.raw);
      isAudio(props.fileType) && localAudioPreview(props.raw);
    } else {
      if (isVideo(props.fileType)) {
        src.value =
          import.meta.env.VITE_APP_BASE_URL +
          "/upload/attachments/getTeamOfVideo?id=" +
          props.id;
        return;
      }
      if (isText(props.fileType)) {
        const response = await axios.get(
          import.meta.env.VITE_STATIC_URL + props.filePath,
          {
            responseType: "text"
          }
        );
        src.value = response.data;
        return;
      }
      src.value = import.meta.env.VITE_STATIC_URL + props.filePath;
    }
  }

  /**
   * 校验图片类型
   * @param type
   */
  function isImage(type: string) {
    const types = [
      "jpg",
      "png",
      "gif",
      "jpeg",
      "bmp",
      "webp",
      "svg",
      "tiff",
      "tif",
      "jpeg",
      "jfif",
      "pjpeg",
      "pjp"
    ];
    return types.includes(type);
  }

  /**
   * 校验文档类型
   * @param type
   */
  function isDoc(type: string) {
    const types = ["docx", "doc", "xlsx", "xls", "pdf"];
    return types.includes(type);
  }

  /**
   * 校验文本类型
   * @param type
   */
  function isText(type: string) {
    const types = [
      "txt",
      "md",
      "log",
      "json",
      "xml",
      "html",
      "css",
      "js",
      "java",
      "c",
      "cpp",
      "h",
      "hpp",
      "py",
      "rb",
      "go",
      "sh",
      "bat",
      "ps1",
      "psm1",
      "ps1xml",
      "psc1",
      "psd1",
      "psm1",
      "ps1xml",
      "psc1",
      "psd1",
      "ps1xml",
      "psc1",
      "ps1xml",
      "psc1",
      "psd1"
    ];
    return types.includes(type);
  }

  // 检验视频格式
  function isVideo(type: string) {
    const types = [
      "mp4",
      "avi",
      "rmvb",
      "mkv",
      "flv",
      "wmv",
      "mov",
      "webm",
      "m4v",
      "mpg",
      "mpeg",
      "3gp",
      "3g2",
      "vob",
      "ogv",
      "ogg",
      "mts",
      "m2ts",
      "ts",
      "m2v",
      "mpe",
      "mpv",
      "m4p",
      "m4v",
      "mpv2",
      "m4v",
      "m4p",
      "m4v",
      "m4p"
    ];
    return types.includes(type);
  }

  // 检验音频文件
  function isAudio(type: string) {
    const types = ["mp3", "wav", "ogg", "flac", "aac", "wma", "m4a", "wma"];
    return types.includes(type);
  }

  /**
   * 预览本地Office文件
   * @param file
   */
  function localOfficePreview(file: File) {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = loadEvent => {
      const arrayBuffer = loadEvent.target.result;
      const blob = new Blob([arrayBuffer], {
        type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      });
      src.value = URL.createObjectURL(blob);
    };
  }

  /**
   * 预览本地图片
   * @param file
   */
  function localImagePreview(file: File) {
    const reader = new FileReader();
    reader.onload = e => {
      src.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }

  /**
   * 预览本地文本
   * @param file
   */
  function localTextPreview(file: File) {
    const reader = new FileReader();
    reader.onload = e => {
      src.value = e.target.result;
    };
    reader.readAsText(file);
  }

  /**
   * 预览本地视频
   * @param file
   */
  function localVideoPreview(file: File) {
    src.value = URL.createObjectURL(file);
  }

  function localAudioPreview(file: File) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const blob = new Blob([reader.result], { type: "audio/mpeg" });
      src.value = URL.createObjectURL(blob);
    };
    reader.readAsArrayBuffer(file);
  }

  // 清理工作：当组件卸载时释放URL对象
  onUnmounted(() => {
    if (src.value) {
      isVideo(props.fileType) && URL.revokeObjectURL(src.value);
      isAudio(props.fileType) && URL.revokeObjectURL(src.value);
    }
  });
  return {
    excelOptions,
    src,
    filePreviewRef,
    isImage,
    renderedHandler,
    errorHandler,
    renderTheFile,
    isVideo,
    isText,
    isAudio
  };
}
